<template>
<div>
 <div class="back-nav">
    <van-icon name="arrow-left" @click="onClickLeft"/>
</div>  
  <div class="login-box">
    <div class="title">欢迎登录</div>
    <van-form @submit="onSubmit">
      <van-cell-group v-if="loginType === 2" inset>
        <van-field
          v-model="email"
          name="email"
          label="邮箱"
          clearable
          placeholder="请填写邮箱"
          :rules="[{ required: true, message: '请填写邮箱' }, {validator, message: '邮箱格式不正确'}]"
        />
        <van-field
          v-model="verificationCode"
          name="captchaCode"
          clearable
          label="验证码"
          placeholder="请填写验证码"
          :rules="[{ required: true, message: '请填写验证码' }]"
        >
          <template #button>
             <span v-if="!showCount" @click="getVerificationCode">{{text}}</span>
             <span v-else>{{times}}秒</span>
          </template>
        </van-field>
      </van-cell-group>
      <van-cell-group v-if="loginType === 1" inset>
          <van-field
              v-model="user_no"
              name="user_no"
              label="账号"
              clearable
              placeholder="请填写账号"
              :rules="[{ required: true, message: '请填写账号' }]"
            />
            <van-field
              v-model="password"
              type="password"
              name="password"
              label="密码"
              clearable
              placeholder="请填写密码"
              :rules="[{ required: true, message: '请填写密码' }]"
            />
            <van-field
              v-model="captchaCode"
              name="captchaCode"
              center
              clearable
              label="验证码"
              :rules="[{ required: true, message: '请填写验证码' }]"
              placeholder="请填写验证码">
              <template #button>
               <div v-html="vImg" style="width: 80px;height: 30px;margin-top: -15px;" @click="getVerifyCode"></div>
              </template>
          </van-field>
      </van-cell-group>
      <div style="margin: 50px 30px 80px 30px">
        <van-button round block type="primary" color="#28AE61" :loading="isLoading" loading-text="登 录 中..." native-type="submit">
          登&nbsp;&nbsp;&nbsp;&nbsp;录
        </van-button>
        <van-divider><span style="color: #4099FF;font-size: 13px;" @click="changeLoginType">{{loginType === 1 ? '邮箱登录' : '账号密码登录'}}</span></van-divider>
      </div>
    </van-form>
  </div>
</div>
</template>
<script lang="ts" setup>
import { ref, reactive, toRefs } from "vue";
import { Toast } from "vant";
import { sendMailer, getCaptchaCode, toLogin } from  '@/api/common'
import { RSAencrypt } from '@/utils/utils';
import { useRoute, useRouter } from "vue-router";
import { useCommonStore } from "@/store/modules/common";

type LOGIN_INFO = {
  user_no: string;
  password: string;
  type: number;
  uuid: string;
  captchaCode: string;
}

const router = useRouter()
const route = useRoute()

const loginType = ref<number>(2)
const isLoading = ref<boolean>(false)
const email = ref<string>("");
const verificationCode = ref<string>("");
const showCount = ref<boolean>(false)
const text = ref<string>("获取验证码")
const times = ref<number>(59);
const vImg = ref<string>("")
const loginInfo = reactive<LOGIN_INFO>({
  user_no: '',
  password: '',
  type: 1,
  uuid: '',
  captchaCode: ''
})
const validator = (val: any) => /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(val)

const { user_no, password, uuid, captchaCode } = toRefs(loginInfo)

const useCommon = useCommonStore();

const changeLoginType = () => {
  loginType.value = loginType.value === 1 ? 2 : 1
  if(loginType.value === 1) {
    getVerifyCode()
  }
}

// 获取邮箱验证码
const getVerificationCode = async () => {
    if(!email.value) {
        return
    }
    if(!validator(email.value)) {
      Toast('邮箱格式不正确')
      return    
    }
    const rsp = await sendMailer({ email: email.value })
    if(rsp.code === 0) {
        Toast.success(rsp.msg)
        times.value = 59
        showCount.value = true
        const interval = setInterval(() => {
            times.value --
            if(times.value < 1) {
                showCount.value = false
                text.value = '重新获取'
                clearInterval(interval)
            }
        }, 1000)
    }
};

// 获取图片验证码
const getVerifyCode = async () => {
  const rsp = await getCaptchaCode({loading: false})
  if(rsp.code === 0) {
    uuid.value = rsp.data.uuid
    vImg.value = rsp.data.img 
  }
}

const onSubmit = async (data: any) => {
  isLoading.value = true
  const info = loginType.value === 1 ? {...data, type: loginType.value, uuid: uuid.value, password: RSAencrypt(password.value)} : {...data, type: loginType.value}
  const rsp = await toLogin(info, { loading: false })
  if(rsp.code === 0) { 
    useCommon.updateUserInfo(rsp.data)
    localStorage.setItem('token', rsp.token) 
    Toast.success('登录成功')
    router.push('/index')
  }
  isLoading.value = false
};


const onClickLeft = () => { 
  if(route && route.query.from === '1') {
    router.push('/')
  }else if(route && route.query.from === 'me'){
    useCommon.updateTabbarActive('index')
    router.push('/index')
  }else {
    router.go(-1)
  }
}

</script>
<style lang="less" scoped>
.back-nav {
  padding: 20px 0 0 10px;
}
.login-box {
  padding: 60px 20px;
  .title {
    color: #333;
    font-size: 18px;
    font-weight: 700;
    letter-spacing: 1px;
    margin: 15px 0 30px 0;
  }
}
</style>
